var wsCommon = {
    host: "http://120.24.1.204:8082",
    jsonType: "jsonp",
    getUrlParam: function(name) {
           var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
           var r = window.location.search.substr(1).match(reg);  //匹配目标参数
           if (r != null) return unescape(r[2]); return null; //返回参数值
    },
    setCookie: function(name, value) {
        var Days = 30;
         var exp = new Date();
         exp.setTime(exp.getTime() + Days*24*60*60*1000);
         document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    },
    getCookie: function(name) {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
         if(arr=document.cookie.match(reg))
         return unescape(arr[2]);
         else
         return null;
    },
    delCookie: function(name) {
        var exp = new Date();
         exp.setTime(exp.getTime() - 1);
         var cval=wsCommon.getCookie(name);
         if(cval!=null)
         document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }
}

$(function() {
    var totalNum = 0;
    var totalPrice = 0;
    var goodsStyleNum = 0;

    window.common = {
        setTopUserInfo: function() {
            // var uid = wsCommon.getCookie('uid');
            // if(uid) {
                $.ajax({
                    url: wsCommon.host + '/api/member/queryUser',
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                if(typeof(res.data.user != 'undefined') && res.data.user != null) {
                                    $('#loginBar_576').hide();
                                    $('#memberBar_576').show();
                                    $('#uname_576').html(res.data.user.username);
                                    // 注册成功写入用户名
                                    if($('[data-role="registerSuccessName"]').length) {
                                        $('[data-role="registerSuccessName"]').html(res.data.user.username)
                                    }
                                }
                            }

                        }
                    },
                    error: function() {
                        // console.log('购物车显示接口返回失败');
                    }
                })
            // }
        },
        toLogin: function() {
            $('.login-btn').on('click', function() {
                wsCommon.setCookie('go_back_link', window.location.href);
                window.location.href = './passport-login.html';
            })
        },
        logout: function() {
            $(document).on('click', '[data-role="logout"]', function() {
                $.ajax({
                    url: wsCommon.host + '/api/member/logout',
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.code == 1) {
                            wsCommon.delCookie('uid');
                            window.location.href = './index.html';
                        }
                    },
                    error: function() {
                        // console.log('购物车显示接口返回失败');
                    }
                })
            })
        },
        throttle: function(callback, wait) {
            var context, args, timeout, result;
            var previous = 0;
            var later = function () {
                previous = new Date;
                timeout  = null;
                result   = callback.apply(context, args);
            };
            return function () {
                var now = new Date;
                var remaining = wait - (now - previous);
                context = this;
                args = arguments;
                if (remaining <= 0) {
                    clearTimeout(timeout);
                    timeout  = null;
                    previous = now;
                    result   = callback.apply(context, args);
                } else if (!timeout) {
                    timeout = setTimeout(later, remaining);
                }
                return result;
            };
        },
        listShopCart: function() {
            /**购物车**/
            $(".minicart").on('mouseenter', common.throttle(function() {
                $(this).addClass("minicart-active");
                totalNum = 0;
                totalPrice = 0;
                goodsStyleNum = 0;

                common.listShopCartAjax(function(res) {
                    common.renderListShopCart(res);
                });
            }, 200)).on('mouseleave', function() {
                $(this).removeClass("minicart-active");
                $('[data-role="shopCartLoading"]').show();
                $('[data-role="minicart-cont"]').html('');
            })

        },
        renderListShopCart: function(res) {
            $('[data-role="shopCartLoading"]').hide();
            var cartList = res.data == null ? [] : res.data.cartList;
            var cartListTpl = '';

            if(!cartList || cartList.length == 0) {
                $('[data-role="shopCartnon"]').show();
                $('.op-cart-number').html(0);
            } else {
                $('[data-role="shopCartnon"]').hide();
                cartListTpl += '<ul class="minicart-list clearfix">';
                $.each(cartList, function(index, item) {
                    var params = JSON.parse(item.params);
                    cartListTpl += '<li class="goods-item">\
                                       <div class="goods-pic">\
                                               <a href="../info.html?goodsId='+item.objIdentArray[1]+'&catId='+item.catId+'"><img src="'+params.image.murl+'"></a>\
                                       </div>\
                                       <div class="goods-info">\
                                         <h3 class="goods-name"><a href="../info.html?goodsId='+item.objIdentArray[1]+'&catId='+item.catId+'">'+params.productName+'</a></h3>\
                                         <div class="goods-price">\
                                           <p>销售价：<span class="p-price">¥'+params.price+'</span></p>\
                                           <p>数量：<span class="p-quantity">'+item.quantity+'</span><span style="cursor:pointer;" class="action-delete" data-objIdent="'+item.objIdent+'"  data-delprice="'+params.price+'" data-delquantity="'+item.quantity+'">移除</span></p>\
                                         </div>\
                                       </div>\
                                    </li>';
                    goodsStyleNum++;
                    totalNum += item.quantity;
                    totalPrice += params.price * item.quantity;
                });

                cartListTpl += '</ul><div class="minicart-info">\
                                    <p>共 <i>'+goodsStyleNum+'</i> 种商品，数量共 <i>'+totalNum+'</i> 件<br>金额总计：<span class="price">¥'+totalPrice.toFixed(2)+'</span></p>\
                                    <p> <a href="./cart1.html" class="btn-tocart">去结算</a> </p>\
                                </div>';
            }

            $('.op-cart-number').html(totalNum)

            $('[data-role="minicart-cont"]').html(cartListTpl);
        },
        slideListShopCart: function() {
            // 添加购物车弹窗关闭
            $("#mini_cart_dialog .popup-btn-close").click(function(){
    			$("#mini_cart_dialog").hide();
                // $('[data-role="slideShopCartLoading"]').show();
    		})

            var height = $(window).height() - 126;
            $(window).on('resize', common.throttle(function() {
                height = $(window).height() - 126;
                $('.minicart-list').css({
                    'height': height + 'px',
                    'overflow-y': 'scroll'
                })
            }, 200))
            var isCarShow = false;
            //迷你购物车
            $('#car').on('click', function() {
                if(isCarShow) {

                    $(".ioc_index,#floatDivBoxs").animate({right:"0px"}, 'fast', function() {
                        $("#floatDivBoxs").find(".minicart-cont").hide();
                    });
                    $("#floatDivBoxs").find(".minicart-cont").animate({right:'-300px'}, 'fast', function() {
                        $('[data-role="slideShopCartLoading"]').show();
                        $('[data-role="shopCartnon"]').hide();
                        $('[data-role="slideShopCart"]').html('');
                    });

                } else {
                    $('[data-role="shopCartnon"]').hide();
                    totalNum = 0;
                    totalPrice = 0;
                    goodsStyleNum = 0;
                    common.listShopCartAjax(function(res) {
                        common.renderSlideListShopCart(res);
                    });

                    $("#floatDivBoxs").find(".minicart-cont").show();
                    $(".ioc_index,#floatDivBoxs").animate({right:"300px"},'fast', function() {
                        $('.minicart-list').css({
                            'height': height + 'px',
                            'overflow-y': 'scroll'
                        })
                    });
                    $("#floatDivBoxs").find(".minicart-cont").animate({right:'0'}, 'fast')
                }

                isCarShow = !isCarShow;
            })

            $("#floatDivBoxs .popup-btn-close").click(function(){
                isCarShow = false;
                $("#floatDivBoxs").find(".minicart-cont").animate({right:'-300px'}, 'fast')
                $(".ioc_index,#floatDivBoxs").animate({right:"0px"},'fast', function() {
                    $('[data-role="slideShopCartLoading"]').show();
                    $('[data-role="shopCartnon"]').hide();
                    $('[data-role="slideShopCart"]').html('');
                });
            });
        },
        renderSlideListShopCart: function(res) {
            var cartList = res.data == null ? [] : res.data.cartList;
            var cartListTpl = '';

            if(!cartList || cartList.length == 0) {
                $('[data-role="shopCartnon"]').show();
                $('.op-cart-number').html(0);
            } else {
                $('[data-role="shopCartnon"]').hide();
                cartListTpl += '<ul class="minicart-list clearfix">';
                $.each(cartList, function(index, item) {
                    var params = JSON.parse(item.params);
                    cartListTpl += '<li class="goods-item">\
                                       <div class="goods-pic">\
                                               <a href="../info.html?goodsId='+item.objIdentArray[1]+'&catId='+item.catId+'"><img src="'+params.image.murl+'"></a>\
                                       </div>\
                                       <div class="goods-info">\
                                         <h3 class="goods-name"><a href="../info.html?goodsId='+item.objIdentArray[1]+'&catId='+item.catId+'">'+params.productName+'</a></h3>\
                                         <div class="goods-price">\
                                           <p>销售价：<span class="p-price">¥'+params.price+'</span></p>\
                                           <p>数量：<span class="p-quantity">'+item.quantity+'</span><span style="cursor:pointer;" class="action-delete" data-objIdent="'+item.objIdent+'" data-delprice="'+params.price+'" data-delquantity="'+item.quantity+'">移除</span></p>\
                                         </div>\
                                       </div>\
                                    </li>';
                    goodsStyleNum++;
                    totalNum += item.quantity;
                    totalPrice += params.price * item.quantity;
                });

                cartListTpl += '</ul><div class="minicart-info">\
                                    <p>共 <i>'+goodsStyleNum+'</i> 种商品，数量共 <i>'+totalNum+'</i> 件<br>金额总计：<span class="price">¥'+totalPrice.toFixed(2)+'</span></p>\
                                    <p> <a href="./cart1.html" class="btn-tocart">去结算</a> </p>\
                                </div>';
            }

            $('[data-role="slideShopCartLoading"]').hide();

            $('[data-role="slideShopCart"]').html(cartListTpl);
        },
        listShopCartAjax: function(cb) {
            $.ajax({
                url: wsCommon.host + '/api/cart/cartView',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    cb(res)
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })
        },
        initShopCartNum: function() {
            common.listShopCartAjax(function(res) {
                var cartList = res.data.cartList == null ? [] : res.data.cartList;

                $.each(cartList, function(index, item) {
                    var params = JSON.parse(item.params);
                    totalNum += item.quantity;
                    goodsStyleNum++;
                    totalPrice += item.quantity * params.price;
                })

                $('.op-cart-number').html(totalNum)
            })
        },

        // 添加到购物车
        addShopCart: function() {
            $(document).on('click', '[data-role="addShopCart"]', function() {
                var $this = $(this);

                var quantity;
                if($this.attr('data-style') == 'info') {
                    quantity = Number($this.closest('li').prev('li').find('.action-quantity-input').val());
                } else {
                    quantity = Number($this.prev('.p-quantity').find('.action-quantity-input').val()) || 1;
                }

                $.ajax({
                    url: wsCommon.host + '/api/cart/addGoods',
                    data: {
                        goodsId: $this.attr('data-goodsid'),
                        productId: $this.attr('data-productid'),
                        objType: $this.attr('data-objtype'),
                        quantity: quantity
                    },
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.code == 1) {
                            var data = (res.data == null) ? [] : res.data;

                            totalNum = 0;
                            totalPrice = 0;
                            goodsStyleNum = 0;
                            $.each(data, function(index, item) {
                                var params = JSON.parse(item.params);
                                totalNum += item.quantity;
                                goodsStyleNum++;
                                totalPrice += item.quantity * params.price;
                            })
                            $('.op-cart-number').html(totalNum);

                            var _thisoffset = $this.offset();
                            var ox;
                        	var oy;
                            if($this.attr('data-style') == 'info') {
                                ox = _thisoffset.left+39;
                                oy = _thisoffset.top+182;
                            } else {
                                ox = _thisoffset.left-8;
                                oy = _thisoffset.top+165;
                            }

             				$("#mini_cart_dialog")
                            .find('.caution-content').html('加入购物车成功。<br>目前选购商品共<em>'+goodsStyleNum+'</em>种<em>'+totalNum+'</em>件。合计：<i class="price">¥'+totalPrice.toFixed(2)+'</i>').end()
                            .css({
             				  "left": ox + 'px',
             				  "top": oy + 'px',
             				}).show();
                        } else {
                            if(res.code == -5) {
                                var _thisoffset = $this.offset();
                 				var ox = _thisoffset.left-8;
                 				var oy = _thisoffset.top+165;
                                $("#mini_cart_dialog")
                                .find('.caution-content').html('库存不足').end()
                                .css({
                 				  "left": ox,
                 				  "top": oy,
                 				}).show();
                            } else {
                                var _thisoffset = $this.offset();
                 				var ox = _thisoffset.left-8;
                 				var oy = _thisoffset.top+165;
                                $("#mini_cart_dialog")
                                .find('.caution-content').html('加入购物车失败').end()
                                .css({
                 				  "left": ox,
                 				  "top": oy,
                 				}).show();
                            }
                        }

                    },
                    error: function() {
                        // console.log('添加到购物车显示接口返回失败');
                    }
                })
            })
        },

        // 删除购物车商品（单个）
        deleteSingleShopCart: function() {
            $(document).on('click', '.action-delete', function() {
                var $this = $(this);

                $.ajax({
                    url: wsCommon.host + '/api/cart/delCart',
                    data: {
                        objIdent: $(this).attr('data-objident')
                    },
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.reason == 'success') {
                            var data = (res.data == null || res.data == '') ? [] : res.data;
                            // totalNum = 0;
                            // totalPrice = 0;
                            // goodsStyleNum = 0;
                            // $.each(data, function(index, item) {
                            //     var params = JSON.parse(item.params);
                            //     totalNum += item.quantity;
                            //     goodsStyleNum++;
                            //     totalPrice += item.quantity * params.price;
                            // })

                            goodsStyleNum -= 1;
                            if(goodsStyleNum == 0) {
                                totalNum = 0;
                                totalPrice = 0;
                                $('[data-role="shopCartnon"]').show();
                                $('.minicart-info').remove();
                            } else {
                                $('[data-role="shopCartnon"]').hide();
                                totalNum -= $this.attr('data-delquantity');
                                totalPrice -= $this.attr('data-delprice') * $this.attr('data-delquantity');
                                $('.minicart-info').html('<p>共 <i>'+goodsStyleNum+'</i> 种商品，数量共 <i>'+totalNum+'</i> 件<br>金额总计：<span class="price">¥'+totalPrice.toFixed(2)+'</span></p><p> <a href="./cart1.html" class="btn-tocart">去结算</a> </p>')
                            }
                            $this.closest('.goods-item').hide();
                            $('.op-cart-number').html(totalNum)
                        } else {
                            // console.log('删除失败');
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        // console.log('购物车商品单个删除接口返回失败');
                    }
                })
            })
        },
        // 显示金额
        showMoney: function(index, res) {
            if(window.location.href.indexOf('cart1') != -1) {
                $('[data-role="allMoney"]').html('¥' + res.data.payResultInfo.totalMoney);
                $('[data-role="saveMoney"]').html('¥' + res.data.payResultInfo.savedMoney);
                $('[data-role="totalMoney"]').html('¥' + res.data.payResultInfo.payMoney);
                $('.subtotal-integral').html(res.data.payResultInfo.giveScore);

                if(index != undefined) {
                    var dom = $('#product_main_items_list tr').eq(index);
                    dom.find('[data-gwjs="saveMoney"]').html('¥' + res.data.buyInfoList[index].saveMoney);
                    dom.find('[data-gwjs="score"]').html('¥' + res.data.buyInfoList[index].score);
                    dom.find('[data-gwjs="real"]').html('¥' + res.data.buyInfoList[index].subtotalPrice);
                }

                // 多级赠送
                var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;
                var giveObjInfostpl = '';
                if(giveObjInfos.length) {
                    $.each(giveObjInfos, function(index, item) {
                        if(item.showSelect) {
                            giveObjInfostpl += '<div class="djzs-item"><div>'+item.ruleName+'</div>';
                            $.each(item.giveObjInfoList, function(indexDir, itemDir) {
                                if(itemDir.fit) {
                                    giveObjInfostpl += '<div class="djzs-item__inner">\
                                                            <a href="./info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'">\
                                                                <img src="'+itemDir.picUrl+'" alt="'+itemDir.objName+'">\
                                                            </a>\
                                                            <div class="djzs-item__inners">\
                                                                <input type="radio" name="rule'+index+'" data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'">\
                                                                <a href="./info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'" title="'+itemDir.objName+'">'+itemDir.objName+'</a>\
                                                            </div>\
                                                        </div>';
                                }
                            })
                            giveObjInfostpl += '</div>';
                        }
                    })
                    giveObjInfostpl += '<div class="djzs-submit">确定</div>';
                } else {
                    giveObjInfostpl += '无';
                }
                $('[data-role="djzs"]').html(giveObjInfostpl == '<div class="djzs-submit">确定</div>' ? '无' : giveObjInfostpl);

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(index, item) {
                    if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            obj[$(item).attr('data-objident')] = Number(i.val());
                        }
                    }
                })
                var objStr = JSON.stringify(obj)
                wsCommon.setCookie('cartIdentInfos', objStr);
            }
        },
        contorlNum: function() {
            //商品数量
            $(document).on('click', '.btn-decrease', function() {
                var $this = $(this);
                var $input = $this.next('input');
                var $x = $input.offset().left;
        		var $y = $input.offset().top;
                var total1 = $(this).attr('data-total');
                var index = $this.closest('tr').index();

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                    if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            if(indexDir == index) {
                                obj[$(item).attr('data-objident')] = Number(i.val()) - 1;
                            } else {
                                obj[$(item).attr('data-objident')] = Number(i.val());
                            }
                        }
                    }
                })
                var objStr = JSON.stringify(obj)

                if($input.val() > 1) {
                    if($this.attr('data-page') == 'cart1') {
                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: Number($input.val()) - 1
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            dataType: wsCommon.jsonType,
                            success: function(res) {
                                if(res.code == 1) {
                                    if(!res.result) {
                                        wsCommon.setCookie('go_back_link', window.location.href);
                                        window.location.href = './passport-login.html';
                                        return;
                                    }
                                    $input.val(parseInt($input.val())-1);
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) - 1);

                                    // 购物车结算
                                    if($('#product_main_items_list').length) {
                                        // var scoredom = $this.closest('td').next('td').next('td');
                                        // scoredom.html(Number(scoredom.attr('data-score')) * Number($input.val()).toFixed(2));
                                        // var chaeDom = scoredom.next('td');
                                        // chaeDom.html('¥' + (Number(chaeDom.attr('data-chae')) * Number($input.val())).toFixed(2));
                                        // var saveDom = $this.closest('td').next('td');
                                        // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($input.val())).toFixed(2));

                                        // var totalScore = 0;
                                        // $.each($('[data-gwjs="score"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalScore += Number($(item).html());
                                        //     }
                                        // })
                                        // $('.subtotal-integral').html(totalScore);
                                        common.showMoney(index, res);
                                        // var totalSavemony = 0;
                                        // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalSavemony += Number($(item).html().substring(1));
                                        //     }
                                        // })
                                        // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
                                        //
                                        // var totalMoney = 0;
                                        // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
                                        //     }
                                        // })
                                        // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
                                        //
                                        // var totalRealMoney = 0;
                                        // $.each($('[data-gwjs="real"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalRealMoney += Number($(item).html().substring(1));
                                        //     }
                                        // })
                                        // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
                                    }
                                } else {
                                    if(res.code == -5) {
                                        var tempcha = Number($input.val()) - Number($this.attr('data-total'));

                                        $.ajax({
                                            url: wsCommon.host + '/api/cart/updateCart',
                                            data: {
                                                updateInfo: JSON.stringify([
                                                    {
                                                        goodsId: $this.attr('data-goodsid'),
                                                        productId: $this.attr('data-productid'),
                                                        objType: $this.attr('data-objtype'),
                                                        quantity: Number($input.val()) - 1
                                                    }
                                                ]),
                                                cartIdentInfos: objStr
                                            },
                                            dataType: wsCommon.jsonType,
                                            success: function(res) {
                                                if(res.code == 1) {
                                                    if(!res.result) {
                                                        wsCommon.setCookie('go_back_link', window.location.href);
                                                        window.location.href = './passport-login.html';
                                                        return;
                                                    }
                                                    $input.val($this.attr('data-total'));
                                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) - tempcha);
                                                    $this.closest('.p-quantity').next('[data-role="tips"]').hide();
                                                    // var scoredom = $this.closest('td').next('td').next('td');
                                                    // scoredom.html(Number(scoredom.attr('data-score')) * Number($input.val()).toFixed(2));
                                                    // var chaeDom = scoredom.next('td');
                                                    // chaeDom.html('¥' + (Number(chaeDom.attr('data-chae')) * Number($input.val())).toFixed(2));
                                                    // var saveDom = $this.closest('td').next('td');
                                                    // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($input.val())).toFixed(2));

                                                    // var totalScore = 0;
                                                    // $.each($('[data-gwjs="score"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalScore += Number($(item).html());
                                                    //     }
                                                    // })
                                                    // $('.subtotal-integral').html(totalScore);
                                                    //
                                                    // var totalSavemony = 0;
                                                    // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalSavemony += Number($(item).html().substring(1));
                                                    //     }
                                                    // })
                                                    // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
                                                    //
                                                    // var totalMoney = 0;
                                                    // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
                                                    //     }
                                                    // })
                                                    // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
                                                    //
                                                    // var totalRealMoney = 0;
                                                    // $.each($('[data-gwjs="real"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalRealMoney += Number($(item).html().substring(1));
                                                    //     }
                                                    // })
                                                    // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
                                                    common.showMoney(index, res);
                                                }
                                            },
                                            error: function() {}
                                        })
                                    } else {
                                        iosOverlay({
                                            text: res.reason,
                                            duration: 1000
                                        });
                                    }
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
                    $input.val($this.next('input').val()-1)
                } else {
                    if(total1 == 0) {
                        $(this).closest('.p-quantity').next('p').show();
                    } else {
                        $("#xtips_txt").html("此商品的最小购买数量为1件");
        				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
        				setTimeout(function () {
        					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
        				}, 1500);
                    }
                }

                var total1 = $(this).attr('data-total');

                if($input.val() <= total1) {
                    $(this).closest('.p-quantity').next('p').hide();
                }


            })
            $(document).on('click', '.btn-increase', function() {
                var $this = $(this);
                var $input = $this.prev('input');
                var $x = $input.offset().left;
        		var $y = $input.offset().top;
                var maxStore = Number($this.attr('data-total'));
                var index = $this.closest('tr').index();

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                    if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            if(indexDir == index) {
                                if(Number(i.val()) >= maxStore) {
                                    obj[$(item).attr('data-objident')] = maxStore;
                                } else {
                                    obj[$(item).attr('data-objident')] = Number(i.val()) + 1;
                                }
                            } else {
                                obj[$(item).attr('data-objident')] = Number(i.val());
                            }
                        }
                    }
                })
                var objStr = JSON.stringify(obj)

                if($input.val()>0 && $input.val() < maxStore) {
                    $this.closest('.p-quantity').next('[data-role="tips"]').hide();
                    if($this.attr('data-page') == 'cart1') {
                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: Number($input.val()) + 1
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            dataType: wsCommon.jsonType,
                            success: function(res) {
                                if(res.code == 1) {
                                    if(!res.result) {
                                        wsCommon.setCookie('go_back_link', window.location.href);
                                        window.location.href = './passport-login.html';
                                        return;
                                    }
                                    $input.val(parseInt($input.val())+1);
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + 1);
                                    // 购物车结算
                                    if($('#product_main_items_list').length) {
                                        // var scoredom = $this.closest('td').next('td').next('td');
                                        // scoredom.html((Number(scoredom.attr('data-score')) * Number($input.val())));
                                        // var chaeDom = scoredom.next('td');
                                        // chaeDom.html('¥' + (Number(chaeDom.attr('data-chae')) * Number($input.val())).toFixed(2));
                                        // var saveDom = $this.closest('td').next('td');
                                        // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($input.val())).toFixed(2));

                                        // var totalScore = 0;
                                        // $.each($('[data-gwjs="score"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalScore += Number($(item).html());
                                        //     }
                                        // })
                                        // $('.subtotal-integral').html(totalScore);
                                        //
                                        // var totalSavemony = 0;
                                        // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalSavemony += Number($(item).html().substring(1));
                                        //     }
                                        // })
                                        // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
                                        //
                                        // var totalMoney = 0;
                                        // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
                                        //     }
                                        // })
                                        // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
                                        //
                                        // var totalRealMoney = 0;
                                        // $.each($('[data-gwjs="real"]'), function(index,item) {
                                        //     if($(item).closest('tr').attr('data-checked') == 1) {
                                        //         totalRealMoney += Number($(item).html().substring(1));
                                        //     }
                                        // })
                                        // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
                                        common.showMoney(index, res);
                                    }
                                } else {
                                    iosOverlay({
                                        text: res.reason,
                                        duration: 1000
                                    });
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
                    $input.val(parseInt($input.val())+1);
                } else {
                    $("#xtips_txt").html("此商品最多只能购买"+maxStore+"件");
    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    				setTimeout(function () {
    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    				}, 1500);
                }


            })

            // $(document).on('keyup', '.action-quantity-input', function() {
            //     var $this = $(this);
            //     var tmptxt=$this.val();
    		// 	$this.val(tmptxt.replace(/\D|^0/g,''));
            //     var $max = Number($this.attr('data-total'));
            //     var $x = $this.offset().left;
        	// 	var $y = $this.offset().top;
    		// 	if(tmptxt>$max){
    		// 		$(this).val($max);
    		// 		$("#xtips_txt").html("此商品最多只能购买"+$max+"件");
    		// 		$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    		// 		setTimeout(function () {
    		// 			$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    		// 		}, 1500);
            //
            //         // if($('#product_main_items_list').length) {
            //         //     var scoredom = $this.closest('td').next('td').next('td');
            //         //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
            //         //     var chaeDom = scoredom.next('td');
            //         //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
            //         // }
    		// 	}else if(tmptxt<1){
    		// 		$(this).val(1);
    		// 		$("#xtips_txt").html("此商品的最小购买数量为1件");
    		// 		$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    		// 		setTimeout(function () {
    		// 			$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    		// 		}, 1500);
            //         if($('#product_main_items_list').length) {
            //             // var scoredom = $this.closest('td').next('td').next('td');
            //             // scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
            //             // var chaeDom = scoredom.next('td');
            //             // chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
            //             // var saveDom = $this.closest('td').next('td');
            //             // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($this.val())));
            //
            //             // var totalScore = 0;
            //             // $.each($('[data-gwjs="score"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalScore += Number($(item).html());
            //             //     }
            //             // })
            //             // $('.subtotal-integral').html(totalScore);
            //             //
            //             // var totalSavemony = 0;
            //             // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalSavemony += Number($(item).html().substring(1));
            //             //     }
            //             // })
            //             // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
            //             //
            //             // var totalMoney = 0;
            //             // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
            //             //     }
            //             // })
            //             // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
            //             //
            //             // var totalRealMoney = 0;
            //             // $.each($('[data-gwjs="real"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalRealMoney += Number($(item).html().substring(1));
            //             //     }
            //             // })
            //             // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
            //             common.showMoney($this.closest('tr').index());
            //         }
    		// 	}
            // });
            var tempval = 0;
            $(document).on('focus', '.action-quantity-input', function() {
                var $this = $(this);
                var tmptxt=$this.val();
                tempval = tmptxt;
            })

            $(document).on('blur', '.action-quantity-input', function() {
                var $this = $(this);
                var tmptxt=$this.val();
    			$this.val(tmptxt.replace(/[^0-9\-]/g,''));
                var $max = Number($this.attr('data-total'));
                var $x = $this.offset().left;
        		var $y = $this.offset().top;

                var index = $this.closest('tr').index();

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                    if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            if(indexDir == index) {
                                if(Number(i.val()) > $max) {
                                    obj[$(item).attr('data-objident')] = $max;
                                } else if(Number(i.val()) < 1) {
                                    obj[$(item).attr('data-objident')] = 1;
                                } else {
                                    obj[$(item).attr('data-objident')] = Number(i.val());
                                }
                            } else {
                                obj[$(item).attr('data-objident')] = Number(i.val());
                            }
                        }
                    }
                })
                var objStr = JSON.stringify(obj)

    			if(tmptxt>$max){
                    $this.closest('.p-quantity').next('[data-role="tips"]').show();
                    if($this.attr('data-page') == 'cart1') {

                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: $max
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            dataType: wsCommon.jsonType,
                            success: function(res) {
                                if(res.code == 1) {
                                    if(!res.result) {
                                        wsCommon.setCookie('go_back_link', window.location.href);
                                        window.location.href = './passport-login.html';
                                        return;
                                    }
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + $max - tempval);
                                    $this.val($max);
                    				$("#xtips_txt").html("此商品最多只能购买"+$max+"件");
                    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
                    				setTimeout(function () {
                    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
                    				}, 1500);

                                    // if($('#product_main_items_list').length) {
                                    //     var scoredom = $this.closest('td').next('td').next('td');
                                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                                    //     var chaeDom = scoredom.next('td');
                                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                                    // }
                                    common.showMoney(index, res);
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }

    				$this.val($max);
    				$("#xtips_txt").html("此商品最多只能购买"+$max+"件");
    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    				setTimeout(function () {
    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    				}, 1500);

                    // if($('#product_main_items_list').length) {
                    //     var scoredom = $this.closest('td').next('td').next('td');
                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                    //     var chaeDom = scoredom.next('td');
                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                    // }
                    common.showMoney($this.closest('tr').index());
    			} else if(tmptxt<1){
                    if($this.attr('data-page') == 'cart1') {

                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: 1
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            dataType: wsCommon.jsonType,
                            success: function(res) {
                                if(res.code == 1) {
                                    if(!res.result) {
                                        wsCommon.setCookie('go_back_link', window.location.href);
                                        window.location.href = './passport-login.html';
                                        return;
                                    }
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + 1 - tempval);
                                    $this.val(1);
                    				$("#xtips_txt").html("此商品的最小购买数量为1件");
                    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
                    				setTimeout(function () {
                    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
                    				}, 1500);
                                    // if($('#product_main_items_list').length) {
                                    //     var scoredom = $this.closest('td').next('td').next('td');
                                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                                    //     var chaeDom = scoredom.next('td');
                                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                                    // }
                                    common.showMoney(index, res);
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
    				$this.val(1);
    				$("#xtips_txt").html("此商品的最小购买数量为1件");
    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    				setTimeout(function () {
    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    				}, 1500);
                    // if($('#product_main_items_list').length) {
                    //     var scoredom = $this.closest('td').next('td').next('td');
                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                    //     var chaeDom = scoredom.next('td');
                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                    // }
    			} else {
                    $this.closest('.p-quantity').next('[data-role="tips"]').hide();
                    if($this.attr('data-page') == 'cart1') {

                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: Number($this.val())
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            dataType: wsCommon.jsonType,
                            success: function(res) {
                                if(res.code == 1) {
                                    if(!res.result) {
                                        wsCommon.setCookie('go_back_link', window.location.href);
                                        window.location.href = './passport-login.html';
                                        return;
                                    }
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + Number($this.val()) - tempval);
                                    if($('#product_main_items_list').length) {
                                        // var scoredom = $this.closest('td').next('td').next('td');
                                        // scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                                        // var chaeDom = scoredom.next('td');
                                        // chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                                        // var saveDom = $this.closest('td').next('td');
                                        // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($this.val())));

                                        // var totalScore = 0;
                                        // $.each($('[data-gwjs="score"]'), function(index,item) {
                                        //     totalScore += Number($(item).html());
                                        // })
                                        // $('.subtotal-integral').html(totalScore);
                                        //
                                        // var totalSavemony = 0;
                                        // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
                                        //     totalSavemony += Number($(item).html().substring(1));
                                        // })
                                        // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
                                        //
                                        // var totalMoney = 0;
                                        // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
                                        //     totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
                                        // })
                                        // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
                                        //
                                        // var totalRealMoney = 0;
                                        // $.each($('[data-gwjs="real"]'), function(index,item) {
                                        //     totalRealMoney += Number($(item).html().substring(1));
                                        // })
                                        // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
                                        common.showMoney(index, res);
                                    }
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
                    if($('#product_main_items_list').length) {
                        // var scoredom = $this.closest('td').next('td').next('td');
                        // scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                        // var chaeDom = scoredom.next('td');
                        // chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                        // var saveDom = $this.closest('td').next('td');
                        // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($this.val())));

                        // var totalScore = 0;
                        // $.each($('[data-gwjs="score"]'), function(index,item) {
                        //     totalScore += Number($(item).html());
                        // })
                        // $('.subtotal-integral').html(totalScore);
                        //
                        // var totalSavemony = 0;
                        // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
                        //     totalSavemony += Number($(item).html().substring(1));
                        // })
                        // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
                        //
                        // var totalMoney = 0;
                        // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
                        //     totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
                        // })
                        // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
                        //
                        // var totalRealMoney = 0;
                        // $.each($('[data-gwjs="real"]'), function(index,item) {
                        //     totalRealMoney += Number($(item).html().substring(1));
                        // })
                        // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
                        common.showMoney(index, res);
                    }
                }
            })
        },
        deleteAllShopCart: function() {
            $(document).on('click', '[data-role="delAll"]', function() {
                $.ajax({
                    url: wsCommon.host + '/api/cart/delAllCart',
                    dataType: wsCommon.jsonType,
                    success: function(res) {

                    },
                    error: function() {
                        // console.log('删除购物车所有赏评接口返回失败');
                    }
                })
            })
        },
        // 浏览记录
        viewHistory: function() {
            $(document).on('click', '.history .clearAll', function() {
                wsCommon.delCookie('view_history');
                $('.history .product-list').html('');
            })
            var viewHistory = wsCommon.getCookie('view_history');
            if(viewHistory == null) {
                return;
            } else {
                $.ajax({
                    url: wsCommon.host + '/api/goods/productHistoryList',
                    dataType: wsCommon.jsonType,
                    data: {
                        productIds: viewHistory
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            var productsList = res.data.productsList ? res.data.productsList : [];

                            var productsListTpl = '';
                            $.each(productsList, function(index,item) {
                                productsListTpl += '<li class="product-item last">\
                                                      <a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank" title="'+item.name+'" class="product-img"><img src="'+item.defaultImage.surl+'"></a>\
                                                      <div class="product-info"><a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank" title="'+item.name+'" class="product-name">'+item.name+'</a><p class="price1"></p></div>\
                                                    </li>';
                            })
                            $('.history .product-list').html(productsListTpl);
                        }
                    },
                    error: function() {
                        // console.log('购物车显示接口返回失败');
                    }
                })
            }

        },
        navList: function() {
            $.ajax({
                url: wsCommon.host + '/api/cat/list',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        var data = res.data.goodsCats;
                        var tpl = '';
                        $.each(data, function(index, item) {
                            var cat2nameTpl = '';
                            var cat3nameTpl = '';

                            var arrorTpl = '';
                            if(item.children == null) {
                                arrorTpl = 'style="background: none"';
                            }

                            var catName = item.catName;
                            var catId = item.catId;

                            $.each(item.children ? item.children : [], function(indexDir, itemDir) {
                                cat2nameTpl += '<a href="./list.html?catId='+itemDir.catId+'" class="level2">'+itemDir.catName+'</a>';
                                cat3nameTpl += '<dl class="sub-category clearfix"><dt><a href="./list.html?catId='+itemDir.catId+'" class="level2">'+itemDir.catName+'</a></dt><dd class="clearfix">'
                                $.each(itemDir.children ? itemDir.children : [], function(index2Dir, item2Dir) {
                                    cat3nameTpl += '<a href="./list.html?catId='+item2Dir.catId+'" class="level3">'+item2Dir.catName+'</a>';
                                })
                                cat3nameTpl += '</dd></dl>';
                            })

                            // 相关品牌
                            var brandTpl = '';
                            var brandList = item.brandList;
                            $.each(brandList, function(brandIndex, brandItem) {
                                brandTpl += '<a href="./brandList.html?brandId='+brandItem.brandId+'" class="item">'+brandItem.brandName+'</a>';
                            })

                            tpl += '<li class="category-item">\
                              <div class="cat-root-box"> <a href="./list.html?catId='+item.catId+'" class="category-link" '+arrorTpl+'>'+item.catName+'</a>\
                                <div class="cat-lv2-redundancy">'+cat2nameTpl+'</div>\
                              </div>\
                              <div class="cat-children-box clearfix" style="top: 0px;">\
                                <div class="cat-children">'+cat3nameTpl+'</div>\
                                <div class="close"></div>\
                                <div class="cat-link">\
                                  <div class="cat-goto"><a href="./list.html?catId='+catId+'" target="_blank">'+catName+'频道</a><i></i></div>\
                                  <dl class="cat-link-brand">\
                                    <dt>相关品牌</dt>\
                                    <dd>'+brandTpl+'</dd>\
                                  </dl>\
                                </div>\
                              </div>\
                            </li>';
                        })

                        $('#category_box .category-list').html(tpl);

                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })

            $('#category_box .category-list').on('click', '.close', function() {
                $(this).parents('.category-item').removeClass('active')
            })
        },
        slideNav: function(data) {
            if($('.sidecat').length == 0) return;
            var catId = wsCommon.getUrlParam('catId');
            $.ajax({
                url: wsCommon.host + '/api/cat/list',
                dataType: wsCommon.jsonType,
                data: {
                    catId: catId
                },
                success: function(res) {
                    if(res.code == 1) {
                        var data = res.data.goodsCats;

                        var tpl = '';

                        $.each(data, function(index, item) {
                            if(index == 0) {
                                var hrefTpl = item.parentId == 0 ? './index.html' : './list.html?catId='+item.parentId
                                $('.cat_parent').html('<a href="'+hrefTpl+'" class="depth-0 e-cat-depth0-current">'+item.parentName+'</a>');
                            }

                            var dir2Tpl = '';
                            var symbolTpl = '';
                            if(item.children != null) {
                                if(item.catId == catId) {
                                    symbolTpl = '<span class="symbols Show sigud" title="隐藏" style="width:10px;height:10px;text-indent:0">-</span>';
                                } else {
                                    symbolTpl = '<span class="symbols Hide sigud" title="隐藏" style="width:10px;height:10px;text-indent:0">+</span>';
                                }
                                $.each(item.children, function(indexDir, itemDir) {
                                    dir2Tpl += '<li class="e-cat-depth-2"><a href="./list.html?catId='+itemDir.catId+'" class="depth-2">'+itemDir.catName+'</a></li>';
                                })
                            }
                            var activeTpl = '';
                            var catDownTpl = 'style="display:none"';
                            if(item.catId == catId) {
                                activeTpl = 'is-active';
                                catDownTpl = 'style="display:block"';
                            }
                            tpl += '<li class="e-cat-depth-1 ">\
                                       <p>\
                                           <a href="./list.html?catId='+item.catId+'" class="depth-1 '+activeTpl+'">'+item.catName+'</a>'+symbolTpl+'</p>\
                                       <ul class="cat-down" '+catDownTpl+'>'+dir2Tpl+'</ul>\
                                    </li>';
                        })
                        $('.sidecat .sidecat-wrap').html(tpl);

                        // 面包屑
                        if($('.Navigation').length) {
                            var breadCrumbs = res.data.breadCrumbs;
                            var breadCrumbsLen = breadCrumbs.length - 1;
                            var breadtpl = '<span><a href="./index.html">首页</a></span>';
                            $.each(breadCrumbs, function(index, item) {
                                if(index == breadCrumbsLen) {
                                    breadtpl += '<span style="margin: 0 4px;">&gt;</span><span class="now">'+item.catName+'</span>';
                                } else {
                                    breadtpl += '<span style="margin: 0 4px;">&gt;</span><span><a href="./list.html?catId='+item.catId+'">'+item.catName+'</a></span>';
                                }
                            })
                            $('.Navigation').append(breadtpl);
                        }


                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })
        },
        navHandle: function() {
            /**菜单**/
    		$("#all-category").hover(function(){
                if(window.location.href.indexOf('index') == -1) $("#category_box").show();
    			},function(){
    			  if(window.location.href.indexOf('index') == -1) $("#category_box").hide();
    			})

         $(document).on('mouseenter', ".category-item", function() {
             if($(this).find('.cat-children').find('dl').length == 0) {

             } else {
                 $(this).addClass("active");
                 var menuindex = $(this).parent().children("li").index($(this));
    			 var menuconH = $(this).children(".cat-children-box").height();
    			 if(menuconH<90*(1+menuindex)){
    				 $(this).children(".cat-children-box").css("top",90*(1+menuindex)-menuconH);
    			 }
             }
         }).on('mouseleave', ".category-item", function() {
             $(this).removeClass("active");
         })

    		/**左侧菜单**/
    		$(document).on('click','.e-cat-depth-1 p',function(){
                if($(this).find('.symbols').length == 0) return;
    			var symbo = $(this).children(".symbols");
    			$(this).next("ul").toggle();
    			if(symbo.hasClass("Show")){
    				symbo.removeClass("Show").addClass("Hide").html("+");
    				}else{
    			    symbo.removeClass("Hide").addClass("Show").html("-");
    				}
    		})
        },
        // 热门搜索词
        hotSearch: function() {
            $.ajax({
                url: './js/hotsearch.json',
                dataType: 'json',
                success: function(res) {
                    if(res.code == 1) {
                        var tpl = '';
                        $.each(res.data, function(index, item) {
                            tpl += '<li><a href="./list.html?catId='+item.catId+'" target="_blank">'+item.name+'</a></li>';
                        })
                        $('.qfnavs').append(tpl);
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function() {}
            })
        },
        topNav: function() {
            $.ajax({
                url: wsCommon.host + '/api/index/queryNav',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        var data = res.data.navMenu;
                        var tpl = '';
            			$.each(data, function(index, item) {
            				var hotImage = '';
            				if(item.hasHot) {
            					hotImage = '<img src="images/gif.gif">';
            				}
            				tpl += '<li><a href="'+item.targetLink+'" target="'+item.targetType+'">'+item.name+hotImage+'</a></li>';
            			})
            			$('.MenuList_571').html(tpl);
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        },
        searchBtn: function() {
            $('[data-role="searchBtn"]').on('click', function() {
                var keyword = $('input[name="search_keywords"]').val();
                if(keyword == '请输入商品关键字') {
                    window.location.href = './search.html?keyword=';
                } else {
                    window.location.href = './search.html?keyword=' + keyword;
                }
            })
            $('input[name="search_keywords"]').on('keypress', function(e) {
                if(e.keyCode == 13) {
                    var keyword = $('input[name="search_keywords"]').val();
                    if(keyword == '请输入商品关键字') {
                        window.location.href = './search.html?keyword=';
                    } else {
                        window.location.href = './search.html?keyword=' + keyword;
                    }
                }
            })


            var keyword = wsCommon.getUrlParam('keyword') || '';
            if(keyword) {
                $('input[name="search_keywords"]').val(decodeURI(escape(keyword)));
            }
        },
        init: function() {
            this.setTopUserInfo();
            this.toLogin();
            this.logout();
            this.initShopCartNum();
            this.listShopCart();
            this.slideListShopCart();
            this.addShopCart();
            this.contorlNum()
            this.deleteSingleShopCart();
            this.deleteAllShopCart();
            this.viewHistory();
            this.topNav();
            this.navList();
            this.slideNav();
            this.navHandle();
            this.hotSearch();
            this.searchBtn();
        }
    }

    common.init();
})
